import 'dart:async';
import 'package:stacked/stacked.dart';
import 'package:vista/shared/services/auth_focus.dart';
import 'package:vista/shared/utils/flash_notifier.dart';
import 'package:vista/shared/widgets/exposure_overlay.dart';

/// 注册视图模型
class RegisterViewModel extends BaseViewModel {
  final AuthFocus _authFocus;

  RegisterViewModel(this._authFocus);

  bool _isPasswordVisible = false;
  bool get isPasswordVisible => _isPasswordVisible;

  bool _isConfirmPasswordVisible = false;
  bool get isConfirmPasswordVisible => _isConfirmPasswordVisible;

  /// 切换密码可见性
  void togglePasswordVisibility() {
    _isPasswordVisible = !_isPasswordVisible;
    notifyListeners();
  }

  /// 切换确认密码可见性
  void toggleConfirmPasswordVisibility() {
    _isConfirmPasswordVisible = !_isConfirmPasswordVisible;
    notifyListeners();
  }

  /// 注册
  Future<bool> performRegister({
    required String account,
    required String username,
    required String password,
    required String confirmPassword,
    String? avatar,
  }) async {
    try {
      // 验证输入
      if (account.isEmpty ||
          username.isEmpty ||
          password.isEmpty ||
          confirmPassword.isEmpty) {
        FlashNotifier.flashError('Please fill in all fields');
        return false;
      }

      // 验证密码长度
      if (password.length < 6) {
        FlashNotifier.flashError('Password must be at least 6 characters');
        return false;
      }

      // 验证密码是否匹配
      if (password != confirmPassword) {
        FlashNotifier.flashError('Passwords do not match');
        return false;
      }

      // 显示加载遮罩
      ExposureOverlay.reveal();
      setBusy(true);

      // 模拟加载两秒
      await Future.delayed(const Duration(seconds: 2));

      await _authFocus.register(
        account: account,
        username: username,
        password: password,
        avatar: 'assets/images/avatar1.png',
      );
      setBusy(false);

      // 隐藏加载遮罩
      ExposureOverlay.conceal();

      FlashNotifier.flashSuccess('Registration successful');
      return true;
    } catch (e) {
      setBusy(false);
      // 隐藏加载遮罩
      ExposureOverlay.conceal();
      final errorMessage = e.toString().replaceAll('Exception: ', '');
      FlashNotifier.flashError(errorMessage);
      return false;
    }
  }
}
